// pages/collections/collections.ts
import { getCollectList, collectDel } from '../../../api/user.js';
import { goToPage } from '../../../config/pages';

interface CollectionItem {
  id: number;
  product_id: number;
  category: string;
  product: {
    id: number;
    image: string;
    store_name: string;
    price: number;
    stock: number;
    [key: string]: any;
  };
  add_time: string;
}

Page({
  data: {
    activeTab: 'all',
    tabs: [
      { key: 'all', name: '全部' },
      { key: 'bulk', name: '散料' },
      { key: 'processing', name: '加工' },
      { key: 'material', name: '材料' },
      { key: 'demand', name: '求购' },
      { key: 'group', name: '拼单' },
    ],
    collections: [] as CollectionItem[],
    filteredCollections: [] as CollectionItem[],
    page: 1,
    limit: 20,
    hasMore: true,
    loading: false,
    isEditMode: false,
    selectedIds: [] as number[],
  },

  onLoad() {
    this.loadCollections();
  },

  onShow() {
    // 重新加载收藏列表（可能有变化）
    this.loadCollections(true);
  },

  // 加载收藏列表
  async loadCollections(refresh = false) {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      if (refresh) {
        this.setData({ page: 1, collections: [], hasMore: true });
      }
      
      wx.showLoading({ title: '加载中...' });
      
      const res = await getCollectList({
        page: this.data.page,
        limit: this.data.limit
      });
      
      wx.hideLoading();
      
      if (res.status === 200 && res.data) {
        const newCollections = res.data.list || res.data || [];
        const allCollections = refresh 
          ? newCollections 
          : [...this.data.collections, ...newCollections];
        
        this.setData({
          collections: allCollections,
          hasMore: newCollections.length >= this.data.limit,
          page: this.data.page + 1,
          loading: false
        });
        
        // 过滤当前分类的收藏
        this.filterCollections();
      } else {
        throw new Error(res.msg || '加载失败');
      }
    } catch (error: any) {
      wx.hideLoading();
      this.setData({ loading: false });
      console.error('加载收藏失败:', error);
      
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
    }
  },

  // 过滤收藏列表
  filterCollections() {
    const { activeTab, collections } = this.data;
    
    if (activeTab === 'all') {
      this.setData({ filteredCollections: collections });
    } else {
      const filtered = collections.filter((item: CollectionItem) => {
        return item.category === activeTab;
      });
      this.setData({ filteredCollections: filtered });
    }
  },

  // 切换标签
  switchTab(e: any) {
    const { tab } = e.currentTarget.dataset;
    this.setData({ 
      activeTab: tab,
      isEditMode: false,
      selectedIds: []
    });
    this.filterCollections();
  },

  // 查看收藏详情
  viewCollection(e: any) {
    const { id, productId, category } = e.currentTarget.dataset;
    
    // 根据类别跳转到不同的详情页
    let url = '';
    switch (category) {
      case 'bulk':
        url = `/pages/bulk-material-detail/bulk-material-detail?id=${productId}`;
        break;
      case 'processing':
        url = `/pages/product-detail/product-detail?id=${productId}&type=processing`;
        break;
      case 'material':
        url = `/pages/product-detail/product-detail?id=${productId}&type=material`;
        break;
      case 'demand':
        url = `/pages/demand-detail/demand-detail?id=${productId}`;
        break;
      case 'group':
        url = `/pages/group-detail/group-detail?id=${productId}`;
        break;
      default:
        wx.showToast({
          title: '暂不支持查看此类型',
          icon: 'none'
        });
        return;
    }
    
    goToPage(url);
  },

  // 切换编辑模式
  editMode() {
    this.setData({ 
      isEditMode: !this.data.isEditMode,
      selectedIds: []
    });
  },

  // 选择/取消选择收藏项
  toggleSelect(e: any) {
    const { id } = e.currentTarget.dataset;
    const { selectedIds } = this.data;
    const index = selectedIds.indexOf(id);
    
    if (index > -1) {
      selectedIds.splice(index, 1);
    } else {
      selectedIds.push(id);
    }
    
    this.setData({ selectedIds });
  },

  // 取消收藏
  async cancelCollect(e: any) {
    const { id, productId, category } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '提示',
      content: '确定要取消收藏吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });
            
            const result = await collectDel({
              id: productId,
              category: category
            });
            
            wx.hideLoading();
            
            if (result.status === 200) {
              wx.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
              
              // 从列表中移除
              const collections = this.data.collections.filter((item: CollectionItem) => {
                return item.id !== id;
              });
              
              this.setData({ collections });
              this.filterCollections();
            } else {
              throw new Error(result.msg || '取消失败');
            }
          } catch (error: any) {
            wx.hideLoading();
            console.error('取消收藏失败:', error);
            
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.msg || '取消失败'),
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 批量取消收藏
  async batchCancel() {
    const { selectedIds } = this.data;
    
    if (selectedIds.length === 0) {
      wx.showToast({
        title: '请选择要取消的收藏',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '提示',
      content: `确定要取消选中的 ${selectedIds.length} 个收藏吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });
            
            // 批量取消收藏
            const promises = selectedIds.map(async (id: number) => {
              const item = this.data.collections.find((c: CollectionItem) => c.id === id);
              if (item) {
                return collectDel({
                  id: item.product_id,
                  category: item.category
                });
              }
            });
            
            await Promise.all(promises);
            
            wx.hideLoading();
            
            wx.showToast({
              title: '已取消收藏',
              icon: 'success'
            });
            
            // 从列表中移除
            const collections = this.data.collections.filter((item: CollectionItem) => {
              return !selectedIds.includes(item.id);
            });
            
            this.setData({ 
              collections,
              selectedIds: [],
              isEditMode: false
            });
            this.filterCollections();
          } catch (error: any) {
            wx.hideLoading();
            console.error('批量取消收藏失败:', error);
            
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.msg || '操作失败'),
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 清空所有收藏
  clearAll() {
    wx.showModal({
      title: '清空收藏',
      content: '确定要清空所有收藏吗？此操作不可恢复！',
      success: async (res) => {
        if (res.confirm) {
          const allIds = this.data.collections.map((item: CollectionItem) => item.id);
          this.setData({ selectedIds: allIds });
          await this.batchCancel();
        }
      },
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadCollections(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadCollections();
    }
  },
});

